package com.yunfeng.web.controller;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.yunfeng.web.pojo.HouseInfo;
import com.yunfeng.web.pojo.QHouseInfo;
import com.yunfeng.web.repository.HouseInfoRepository;
import com.yunfeng.web.service.HouseInfoService;
import com.yunfeng.web.util.CommonReturn;
import com.yunfeng.web.util.Constants;
import com.yunfeng.web.util.Result;
import com.yunfeng.web.util.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


@Api("房源管理")
@RestController
public class HouseInfoController {

    @Autowired
    HouseInfoRepository houseInfoRepository;

    //实体管理者
    @Autowired
    EntityManager entityManager;

    //Service层
    @Autowired
    HouseInfoService houseInfoService;

    //格式化工具
    private ResultGenerator<HouseInfo> resultGenerator;

    //DSL实体类
    private QHouseInfo qHouseInfo;

    //JPA查询工厂
    private JPAQueryFactory queryFactory;

    @PostConstruct
    public void initFactory() {
        queryFactory = new JPAQueryFactory(entityManager);
        resultGenerator = new ResultGenerator<>();
        qHouseInfo = QHouseInfo.houseInfo;
        System.out.println("init JPAQueryFactory successfully");
    }


    @RequestMapping("/hello")
    @ResponseBody
    public void helloTest(HttpServletResponse res) {
        try {
            res.getWriter().write("Hello");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入新数据
     *
     * @param houseName  房源名
     * @param houseMj    房源面积
     * @param houseModel 房源户型
     * @param ownerName  业主姓名
     * @param housePrice 房源售价
     * @param ownerPhone 业主联系方式
     */
    @ApiOperation("添加房源信息")
    @RequestMapping("/addHouse")
    @ResponseBody
    public void addHouseInfo(@RequestParam(value = "houseName") String houseName, @RequestParam(value = "houseMj") String houseMj,
                             @RequestParam(value = "housePrice") String housePrice, @RequestParam(value = "houseModel") String houseModel,
                             @RequestParam(value = "ownerName") String ownerName, @RequestParam(value = "ownerPhone") String ownerPhone,
                             HttpServletRequest req, HttpServletResponse res) throws IOException {

        //设置 编码格式
        req.setCharacterEncoding("utf-8");
        res.setContentType("application/json;charset=utf-8");

        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setHouseId(UUID.randomUUID().toString());
        houseInfo.setHouseName(houseName);
        houseInfo.setHouseMj(houseMj);
        houseInfo.setHouseModel(houseModel);
        houseInfo.setOwnerName(ownerName);
        houseInfo.setHousePrice(housePrice);
        houseInfo.setOwnerPhone(ownerPhone);
        try {
            if (houseInfoRepository.save(houseInfo) != null)
                res.getWriter().write(CommonReturn.toPrint(1, "插入成功"));
        } catch (Exception e) {
            res.getWriter().write(CommonReturn.toPrint(-1, e.toString()));
        }
    }

    /**
     * 房源ID删除房源
     */
    @ApiOperation("根据房源Id删除房源")
    @RequestMapping("/deleteById")
    @ResponseBody
    @Transactional
    public void deleteHouseById(@RequestParam(value = "houseId") String houseId, HttpServletRequest req, HttpServletResponse res) throws IOException {
        //设置 编码格式
        req.setCharacterEncoding("utf-8");
        res.setContentType("application/json;charset=utf-8");
        HouseInfo houseInfo = queryFactory.selectFrom(qHouseInfo).where(qHouseInfo.HouseId.eq(houseId)).fetchOne();
        if (houseInfo == null) {
            res.getWriter().write(CommonReturn.toPrint(-1, "没有该房源"));

        } else {
            long i = queryFactory.delete(qHouseInfo).where(qHouseInfo.HouseId.eq(houseId)).execute();
            if (i == 0) {
                res.getWriter().write(CommonReturn.toPrint(0, "删除失败"));
            } else {
                res.getWriter().write(CommonReturn.toPrint(1, "删除成功"));
            }
        }
    }

    /**
     * 房源列表
     */
    @ApiOperation("房源列表获取")
    @RequestMapping("/getAll")
    @ResponseBody
    public List<HouseInfo> queryAll() {
        //使用querydsl查询
        QHouseInfo _Q_user = QHouseInfo.houseInfo;
        //查询并返回结果集
        return queryFactory
                .selectFrom(_Q_user)//查询源
                .orderBy(_Q_user.Id.asc())//根据id倒序
                .fetch();//执行查询并获取结果集
    }

    @RequestMapping(value = "/housebyconditions")
    @ResponseBody
    public List<HouseInfo> getHouseInfoByConditions(@QuerydslPredicate(root = HouseInfo.class) Predicate predicate, Pageable pageable) {
        return houseInfoService.findSearch(predicate, pageable).getContent();
    }

    @RequestMapping(value = "/SelectHouse", method = RequestMethod.GET)
    @ResponseBody
    public Result<HouseInfo> getHouseByConditions(@RequestParam(value = "houseName") String HouseName, @RequestParam(value = "ownerName", required = false, defaultValue = "") String OwnerName,
                                                  @RequestParam(value = "page") int Page) {

        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qHouseInfo.OwnerName.eq(OwnerName));
        builder.or(qHouseInfo.HouseName.eq(HouseName));

        QueryResults<HouseInfo> results = queryFactory.selectFrom(qHouseInfo).orderBy(qHouseInfo.Id.asc())
                .where(builder).limit(5).offset(Page * 5).fetchResults();
        //总条数
        System.out.println(queryFactory.selectFrom(qHouseInfo).fetchCount());

        Result<HouseInfo> result;
        if (results.getResults() != null) {
            if (results.getResults().size() > 0) {
                result = resultGenerator.getSuccessResult();
            } else {
                result = resultGenerator.getSuccessResultWithMemo(Constants.RESULT_CODE_BAD_REQUEST, "没有数据");
            }
            result.setData(results.getResults());
        } else {
            result = resultGenerator.getFailResult("查询失败,无数据");
        }
        return result;
    }
}
